package com.fanshilz.flower2025.apps.admin.aliyun.controller;

import cn.hutool.core.lang.Assert;
import com.fanshilz.flower2025.apps.admin.aliyun.req.AttachmentRemoveReq;
import com.fanshilz.flower2025.apps.admin.aliyun.req.AttachmentUploadReq;
import com.fanshilz.flower2025.business.flower.attachment.entity.Attachment;
import com.fanshilz.flower2025.business.flower.attachment.service.IAttachmentService;
import com.fanshilz.flower2025.framework.aliyun.sts.AliyunSts;
import com.fanshilz.flower2025.framework.aliyun.sts.AliyunStsUtil;
import com.fanshilz.flower2025.framework.resp.Resp;
import io.github.linpeilie.Converter;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/admin/aliyun")
public class AliyunController {

    @Resource
    private Converter converter;
    @Resource
    private IAttachmentService attachmentService;

    @PostMapping("/ststoken/get")
    public Resp<AliyunSts> get() {
        return Resp.success(AliyunStsUtil.get());
    }

    @PostMapping("/attachmentUpload")
    public Resp<Void> attachmentUpload(@RequestBody @Valid AttachmentUploadReq req) {
        Attachment a = converter.convert(req, Attachment.class);
        boolean save = attachmentService.save(a);
        Assert.isTrue(save);
        return Resp.success();
    }

    @PostMapping("/attachmentRemove")
    public Resp<Void> attachmentRemove(@RequestBody @Valid AttachmentRemoveReq req) {
        List<Attachment> attachments = req.getAttachmentIds().stream().map(id -> Attachment.builder()
                .fileId(id)
                .delFlag(true)
                .build()).collect(Collectors.toList());
        boolean b = attachmentService.updateBatch(attachments);
        Assert.isTrue(b);
        return Resp.success();
    }

}
